<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;
use DB;

class Workqrcodeimg extends Model
{
    protected $table = 'work_qrcode_img';
    protected $primaryKey = 'id';

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    public static function previewWorkQrcodeImg($kfid)
    {
        return self::select("img_url")->where("kfid",$kfid)->where("status",1)->orderBy("id","DESC")->first();
    }

    public static function createWorkQrcodeImg($kfid,$name,$img_url,$expiration_time,$count_limit,$rate)
    {
        return self::insert(["kfid"=>$kfid,"name"=>$name,"img_url"=>$img_url,"expiration_time"=>$expiration_time,"count_limit"=>$count_limit,"rate"=>$rate,"created_at"=>time()]);
    }

    public static function batchCreateWorkQrcodeImg($workQrcodeImg)
    {
        return self::insert($workQrcodeImg);
    }

    public static function getWorkQrcodeImgLists($kfid,$limit,$name,$sort,$order)
    {
        $query = self::select("*")->where("kfid",$kfid)->whereIn("status",[1,2]);
        if (!empty($name)) $query->where("name","like","%".$name."%");
        if(!empty($sort) && !empty($order)) $query->orderBy($sort,$order);
        return $query->orderBy("id","DESC")->paginate($limit);
    }

    public static function getKfQrcodeCount($kfid){
        return self::where("kfid",$kfid)->whereIn("status",[1,2])->count();
    }

    public static function getKfImgById($id){
        return self::where("id",$id)->whereIn("status",[1,2])->first();
    }

    public static function updateWorkQrcodeImg($id,$workQrcodeImg)
    {
        return self::where("id",$id)->update($workQrcodeImg);
    }
    
    public static function updateWorkQrcodeImgScan($id,$scan_total,$scan_today)
    {
        return self::where("id",$id)->update(["scan_total"=>$scan_total,"scan_today"=>$scan_today]);
    }

    public static function getAllWorkQrcodeImg($kfid)
    {
        return self::select("id","img_url","expiration_time","count_limit","scan_total","scan_today","rate")->where("kfid",$kfid)->where("expiration_time",">",time()+1800)->where("status",1)->get();
    }
}
